//
//  FindCarTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/8.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "FindCarTableViewController.h"
#import "CarResMode.h"
#import "CarbrandModel.h"
#import "SearchTableViewController.h"
#import "CarpingpaiTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "CarCartoryTableViewController.h"
#import "SearchMode.h"
#import "Puser.h"
#import "LoadingView.h"
#import "Brand.h"
#import "CZSearchBar.h"
#import "CarTableViewController.h"
@interface FindCarTableViewController ()<UITextFieldDelegate,SearchTableViewDelegate>
{
    BOOL isloading;
    BOOL isfirst;
}
@property (nonatomic,weak) CZSearchBar *search;
@property (nonatomic,strong) NSArray *indexarray;
@property (nonatomic,strong) UILabel *lable;
@property (nonatomic,strong) NSMutableArray *data;
@property (nonatomic,strong) NSMutableArray *setecionarray;
@property (nonatomic,strong) UIView *lableview;
@property (nonatomic,strong) UILabel *textlable;
@property (nonatomic,assign) CGFloat showtime;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) LoadingView *loadingview;

@end

@implementation FindCarTableViewController
+(instancetype)findcar{
    FindCarTableViewController *fcvc=[[FindCarTableViewController alloc]initWithNibName:@"FindCarTableViewController" bundle:nil];
    fcvc.hidesBottomBarWhenPushed=YES;
    return fcvc;
}
-(LoadingView *)loadingview{
    if (_loadingview==nil) {
        _loadingview=[LoadingView loading];
        _loadingview.frame=self.tableView.bounds;
        [self.tableView insertSubview:_loadingview atIndex:0];
    }
    return _loadingview;
}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"车源";
    self.navigationItem.leftBarButtonItem=nil;
    [self setupsearch];
    [self setupLable];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (isloading) {
//        if ([_delegate respondsToSelector:@selector(loadingCompleted)]) {
//            [_delegate loadingCompleted];
//        }
//    }
}


-(void)searchCilck:(PUSHTYPE)type WithString:(NSString *)string{
    
    CarTableViewController *carvc=[[CarTableViewController alloc]initWithStyle:UITableViewStylePlain];
    carvc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:carvc animated:YES];
//    if ([_delegate respondsToSelector:@selector(needSwitch)]) {
////        [_delegate needSwitch];
//    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    SearchTableViewController *searchvc=[SearchTableViewController viewController];
    searchvc.modalPresentationStyle=UIModalPresentationOverFullScreen;
    searchvc.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
    searchvc.delegate=self;
    [self presentViewController:searchvc animated:YES completion:^{
        
    }];
    [textField endEditing:YES];
    
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [searchBar endEditing:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view becomeFirstResponder];
}

-(void)setupLable{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake((XHScreenwidth-60)*0.5,(XHScreenheight-60)*0.5, 60, 60)];
    view.backgroundColor=RGBACOLOR(30, 30, 30, 0.7);
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(12, 12, 60-24, 60-24)];
    lable.font=[UIFont systemFontOfSize:20];
    lable.textColor=[UIColor whiteColor];
    lable.textAlignment=NSTextAlignmentCenter;
    view.layer.cornerRadius=30;
    view.clipsToBounds=YES;
    [view addSubview:lable];
    self.textlable=lable;
    self.lableview=view;
}

-(void)showlableview:(NSString *)text{
    self.textlable.text=text;
    
    [self.navigationController.view addSubview:self.lableview];
    
}

-(void)hidelable{
    
    [self.lableview removeFromSuperview];
    
}

-(void)setupsearch{
    
    
    if (!self.type) {
        
        CZSearchBar *search=[[CZSearchBar alloc]initWithFrame:CGRectMake(16, 8, XHScreenwidth-32, 30)];
        search.placeholder=@"可输入品牌、车型、车源类型、配置";
        search.background=[UIImage imageWithStretchableName:@"searchbar_textfield_background"];
        search.font=[UIFont systemFontOfSize:14];
        
        
        
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, 56)];
        
        [view addSubview:search];
        self.search=search;
        self.search.delegate=self;
        self.tableView.tableHeaderView=view;
    }
    self.tableView.backgroundColor=UIColorWithRGB(242, 242, 242);
    //改变索引的颜色
    self.tableView.sectionIndexColor = [UIColor grayColor];
    //改变索引选中的背景颜色
    self.tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexBackgroundColor=[UIColor clearColor];
    UINib *nib=[UINib nibWithNibName:@"CarpingpaiTableViewCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"pingpai"];
    
    [self setupdata];
}

-(void)viewDidAppear:(BOOL)animated{
    [self needupdatehistory];
}

-(void)needupdatehistory{
    if (isfirst) {
        [self gethistroy];
        
    }
}

-(void)gethistroy{
    int power=[self.user.power intValue];
    NSMutableDictionary *historyparams=[NSMutableDictionary dictionary];
    historyparams[@"action"]=@"near_brand";
    if (power<5) {
        historyparams[@"type"]=@"person";
        historyparams[@"user_id"]=self.user.user_id;
    }else{
        historyparams[@"type"]=@"company";
        historyparams[@"user_id"]=self.user.com_id;
        if (power==8) {
            historyparams[@"pid"]=self.user.parent_id;
        }
        
    }
    [PostUitls Post:myhistoryurl parameters:historyparams success:^(id response) {
        CarResMode *res=[CarResMode carResWithDict:response];
        if ([res.state integerValue]==400) {
            [self.data replaceObjectAtIndex:0 withObject:res.data];
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(void)setupdata{
   
    if (self.type) {
        [self getbarnd];
    }else{
        int power=[self.user.power intValue];
        NSMutableDictionary *historyparams=[NSMutableDictionary dictionary];
        historyparams[@"action"]=@"near_brand";
        if (power<5) {
            historyparams[@"type"]=@"person";
            historyparams[@"user_id"]=self.user.user_id;
        }else{
            historyparams[@"type"]=@"company";
            historyparams[@"user_id"]=self.user.com_id;
            if (power==8) {
                historyparams[@"pid"]=self.user.parent_id;
            }
            
        }
        
        [PostUitls Post:myhistoryurl parameters:historyparams success:^(id response) {
            CarResMode *res=[CarResMode carResWithDict:response];
            if ([res.state integerValue]==400) {
                [self.data addObject:res.data];
                
                [self getbarnd];
            }
            
        } failure:^(NSError *error) {
            
        }];
        
    }
    
}

-(void)getbarnd{
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    if (self.type) {
        isfirst=NO;
        params[@"action"]=@"cat";
        params[@"type"]=self.type;
    }else{
        isfirst=YES;
        params[@"action"]=@"all";
    }
    
    [PostUitls Post:carlisturl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        
        CarResMode *res=[CarResMode carResWithDict:dict];
        
        [self setupsetection:res.data];
        
    } failure:^(NSError *error) {
//        if ([_delegate respondsToSelector:@selector(loadingCompleted)]) {
//            [_delegate loadingCompleted];
//        }
//        self.loadingview.hidden=YES;
        NSLog(@"%@",error);
    }];
    
}
-(void)setupsetection:(NSArray *)array{
    CarbrandModel *car=array[0];
    NSString *des=car.brand_desc;
    NSMutableArray *dataarray=[NSMutableArray array];
    if (self.type) {
        
        
        [self.setecionarray addObject:des];
        
    }else{
        
        [self.setecionarray addObject:@"★"];
        [self.setecionarray addObject:des];
        
    }
    
    for (int i=0; i<array.count; i++) {
        CarbrandModel *car=array[i];
        
        if (![car.brand_desc isEqualToString:des]) {
            [self.data addObject:dataarray];
            dataarray=[NSMutableArray array];
            des=car.brand_desc;
            [self.setecionarray addObject:des];
        }
        [dataarray addObject:car];
        if (i==array.count-1) {
            [self.data addObject:dataarray];
            [self.setecionarray addObject:@"#"];
        }
    }
    
    
    [self.tableView reloadData];
    self.loadingview.hidden=YES;
    isloading=YES;
    isfirst=YES;
    if ([_delegate respondsToSelector:@selector(loadingCompleted)]) {
        [_delegate loadingCompleted];
    }
//    NSLog(@"%@",self.data);
}
-(NSMutableArray *)setecionarray{
    if (_setecionarray==nil) {
        _setecionarray=[NSMutableArray array];
    }
    return _setecionarray;
}
-(NSMutableArray *)data{
    if (_data==nil) {
        _data=[NSMutableArray array];
    }
    return _data;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//-(UILabel *)lable{
//    if (_lable==nil) {
//        _lable=[[UILabel alloc]initWithFrame:CGRectMake((XHScreenwidth-60)*0.5, (XHScreenheight-60)*0.5, 60, 60)];
//        _lable.backgroundColor=[[UIColor alloc]initWithRed:25/255.0 green:25/255.0 blue:25/255.0 alpha:0.5];
//        _lable.textAlignment=NSTextAlignmentCenter;
//        _lable.font=[UIFont systemFontOfSize:16];
//        _lable.textColor=[UIColor whiteColor];
//        [self.view.window addSubview: _lable];
//        _lable.hidden=YES;
//    }
//    return _lable;
//}


#pragma mark - Table view data source
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    if (self.setecionarray.count==0) {
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }else{
        tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    }
    return self.setecionarray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if(section==self.setecionarray.count-1){
        return 0;
    }
    else{
        NSArray *array=self.data[section];
        return array.count;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.data[indexPath.section];
    CarbrandModel *mode=array[indexPath.row];
    CarCartoryTableViewController *ccvc=[CarCartoryTableViewController viewcontroller];
    
    ccvc.isFromfind=YES;
    
    ccvc.type=self.type;
    ccvc.mode=mode;
    ccvc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ccvc animated:YES];
    
}

-(void)dealloc{
    //    [self.lable removeFromSuperview];
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = UIColorWithRGB(242, 242, 242);
    
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:UIColorWithRGB(138, 138, 138)];
    [header.textLabel setFont:[UIFont systemFontOfSize:14]];
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    
    
    
    if (section==0&&!self.type) {
        return [NSString stringWithFormat:@"%@ 最近浏览",self.setecionarray[section]];
    }else if(section==self.setecionarray.count-1)
    {
        return nil;
    }
    else{
        return self.setecionarray[section];
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    if (self.view.hidden==NO) {
        [self showlableview:self.setecionarray[index]];
        self.showtime=1.0f;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.showtime=0.8f;
        });
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.showtime==0.8f) {
                self.showtime=0.6f;
            }
            
        });
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.showtime==0.6f) {
                self.showtime=0.4f;
            }
            
        });
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.showtime==0.4f) {
                self.showtime=0.2f;
            }
            
        });
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.showtime==0.2f) {
                [self hidelable];
            }
        });
        
    }
    if (index==self.setecionarray.count-1) {
        return 0;
    }
    
    return index;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.setecionarray;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarpingpaiTableViewCell *cell=[CarpingpaiTableViewCell cellWithTablview:tableView];
    if(indexPath.section==self.setecionarray.count-1){
        return cell;
    }else{
        NSArray *array=self.data[indexPath.section];
        CarbrandModel *carmode=array[indexPath.row];
        cell.listtext.text=carmode.brand_name;
        cell.listtext.textColor=UIColorWithRGB(75, 75, 75);
        cell.listtext.font=[UIFont systemFontOfSize:14];
        NSString *url=[NSString stringWithFormat:@"%@%@",websitehosturl,[carmode.brand_logo stringByReplacingCharactersInRange:NSRangeFromString(@"./") withString:@"/"]];
        [cell.listicon sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placehoder"]];
        return cell;
    }
    
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Table view delegate
 
 // In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Navigation logic may go here, for example:
 // Create the next view controller.
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
 
 // Pass the selected object to the new view controller.
 
 // Push the view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
